import 'dart:async';

import 'package:ai/page/web_view/web_view_page.dart';
import 'package:ai/response/BaseResponse.dart';
import 'package:ai/service/LoginService.dart';
import 'package:ai/util/CommonUtils.dart';
import 'package:ai/util/SharedPreferencesUtil.dart';
import 'package:ai/util/ToastUtils.dart';
import 'package:auto_route/annotations.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

import '../../config/Config.dart';

@RoutePage()
class LoginPage extends StatefulWidget {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final LoginService loginService = LoginService();

  late bool agree = false;
  late String mobile = "";
  late String code = "";

  late bool loading = false;

  late int _start = 0;
  Timer? _timer;

  void startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (_start == 0) {
        setState(() {
          timer.cancel();
          loading = false;
        });
      } else {
        setState(() {
          _start--;
        });
      }
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 16),
        child: ListView(
          children: <Widget>[
            const SizedBox(
              height: 120,
            ),
            const Text(
              "账号登录",
              style: TextStyle(
                fontSize: 40,
              ),
            ),
            const SizedBox(
              height: 24,
            ),
            TextField(
              style: TextStyle(
                color: Config.color9a,
              ),
              onChanged: (val) {
                setState(() {
                  mobile = val;
                });
              },
              keyboardType: TextInputType.phone,
              decoration: InputDecoration(
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Config.color69f,
                    width: 1,
                  ),
                  borderRadius: BorderRadius.circular(4),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Config.color69f,
                    width: 2,
                  ),
                  borderRadius: BorderRadius.circular(4),
                ),
                prefixIcon: Icon(
                  Icons.phone_android,
                  color: Config.color69f,
                ),
                hintText: "请输入手机号",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              maxLines: 1,
            ),
            const SizedBox(
              height: 24,
            ),
            TextField(
              style: TextStyle(
                color: Config.color9a,
              ),
              onChanged: (val) {
                setState(() {
                  code = val;
                });
              },
              keyboardType: TextInputType.number,
              decoration: InputDecoration(
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Config.color69f,
                    width: 1,
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: Config.color69f,
                    width: 2,
                  ),
                  borderRadius: BorderRadius.circular(8),
                ),
                prefixIcon: Icon(
                  Icons.code,
                  color: Config.color69f,
                ),
                suffix: GestureDetector(
                  onTap: () async {
                    if (loading || _start > 0) {
                      return;
                    }
                    RegExp regex = RegExp(r'^1[3-9]\d{9}$');
                    if (regex.hasMatch(mobile)) {
                      var result = await loginService.sendCode({
                        'mobile': mobile,
                        'type': 0,
                      });
                      setState(() {
                        loading = true;
                        _start = 120;
                      });
                      startTimer();
                      if (context.mounted) {
                        if (result.code == 0) {
                          ToastUtils.success(context, "验证码发送成功");
                        } else {
                          ToastUtils.error(context, result.msg);
                        }
                      }
                    } else {
                      ToastUtils.error(context, "手机号格式正确");
                    }
                  },
                  child: loading
                      ? Text(
                          "获取验证码($_start)",
                          style: TextStyle(
                            color: Config.color9,
                            fontSize: 14,
                          ),
                        )
                      : Text(
                          "获取验证码",
                          style: TextStyle(
                            color: Config.colorEc5356,
                          ),
                        ),
                ),
                hintText: "请输入验证码",
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(4),
                ),
              ),
              maxLines: 1,
            ),
            const SizedBox(
              height: 24,
            ),
            FilledButton(
              style: ButtonStyle(
                backgroundColor: WidgetStateProperty.all(Config.color69f),
              ),
              onPressed: () {
                if (!agree) {
                  openDialog();
                } else {
                  /// 请求登录接口。注意判断，获取验证码的手机号是否跟现在的手机号一致
                  loginService.login({
                    'mobile':mobile,
                    'code':code,
                  }).then((result){
                    if(result.code==0){
                      SharedPreferencesUtil().setString("token", result.data);
                      ToastUtils.success(context, "登录成功");
                      CommonUtils.back(context);
                    }else{
                      ToastUtils.error(context, result.msg);
                    }
                  });
                }
              },
              child: const Text("登录"),
            ),
            Row(
              children: [
                Checkbox(
                  side: BorderSide(
                    color: Config.color636977,
                    width: 2.0,
                  ),
                  activeColor: Config.color69f,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(24),
                  ),
                  value: agree,
                  onChanged: (val) {
                    setState(() {
                      agree = val!;
                    });
                  },
                ),
                RichText(
                  text: TextSpan(
                    text: "我已阅读并同意",
                    style: TextStyle(
                      color: Config.color9,
                      fontSize: 12,
                    ),
                    children: [
                      TextSpan(
                        text: "《用户服务条款》",
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xff618fe4),
                        ),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            // 点击后跳转到 WebView 页面
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => const WebViewPage(
                                  url: 'https://member.igomall.xin/privacy',
                                  title: "用户服务条款",
                                ),
                              ),
                            );
                          },
                      ),
                      TextSpan(
                        text: "及",
                        style: TextStyle(
                          fontSize: 12,
                          color: Config.color9,
                        ),
                      ),
                      TextSpan(
                        text: "《隐私政策》",
                        style: const TextStyle(
                          fontSize: 12,
                          color: Color(0xff618fe4),
                        ),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            // 点击后跳转到 WebView 页面
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                builder: (context) => const WebViewPage(
                                  url: 'https://member.igomall.xin/privacy',
                                  title: "隐私政策",
                                ),
                              ),
                            );
                          },
                      ),
                    ],
                  ),
                ),
              ],
            )
          ],
        ),
      ),
    );
  }

  void openDialog() {
    CommonUtils.openModalBottomSheet(
      context,
      child: Container(
        height: 200,
        child: Column(
          children: [
            Row(
              children: [
                Expanded(child: Container()),
                IconButton(
                  onPressed: () {
                    Navigator.pop(context);
                  },
                  icon: Icon(
                    Icons.close,
                    color: Config.color3,
                  ),
                ),
                const SizedBox(
                  width: 16,
                )
              ],
            ),
            const SizedBox(
              height: 8,
            ),
            const Text(
              "请阅读并同意以下条款",
              textAlign: TextAlign.center,
            ),
            const SizedBox(
              height: 8,
            ),
            RichText(
              text: TextSpan(
                text: "",
                style: TextStyle(
                  color: Config.color9,
                  fontSize: 12,
                ),
                children: [
                  TextSpan(
                    text: "《用户服务条款》",
                    style: const TextStyle(
                      fontSize: 12,
                      color: Color(0xff618fe4),
                    ),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const WebViewPage(
                              url: 'https://member.igomall.xin/privacy',
                              title: "用户服务条款",
                            ),
                          ),
                        );
                      },
                  ),
                  TextSpan(
                    text: " ",
                    style: TextStyle(
                      fontSize: 12,
                      color: Config.color9,
                    ),
                  ),
                  TextSpan(
                    text: "《隐私政策》",
                    style: const TextStyle(
                      fontSize: 12,
                      color: Color(0xff618fe4),
                    ),
                    recognizer: TapGestureRecognizer()
                      ..onTap = () {
                        Navigator.push(
                          context,
                          MaterialPageRoute(
                            builder: (context) => const WebViewPage(
                              url: 'https://member.igomall.xin/privacy',
                              title: "隐私政策",
                            ),
                          ),
                        );
                      },
                  ),
                ],
              ),
            ),
            const SizedBox(
              height: 16,
            ),
            Container(
              width: 400,
              padding: const EdgeInsets.symmetric(horizontal: 32),
              child: Expanded(
                child: SizedBox(
                  width: double.infinity,
                  child: FilledButton(
                    style: FilledButton.styleFrom(
                      backgroundColor: Config.primaryColor,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    onPressed: () {
                      setState(() {
                        agree = true;
                      });
                      Navigator.pop(context);
                    },
                    child: const Text('同意并继续'),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
